﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SubSonic;
using ExtAspNet;
using System.Data;
using Newtonsoft.Json.Linq;
using AspNet = System.Web.UI.WebControls;

namespace TCMSystem.admin
{
    public partial class role_module : PageBase
    {
        private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        #region Module

        /// <summary>
        /// 当前页面所属的模块
        /// </summary>
        public override ModuleType Module
        {
            get
            {
                return ModuleType.CoreRoleModule;
            }
        }

        #endregion

        #region Page_Load

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadData();
            }
        }

        private void LoadData()
        {
            // 每页记录数
            Grid1.PageSize = XConfigHelper.PageSize;
            BindGrid();
            // 默认选中第一个角色
            Grid1.SelectedRowIndex = 0;

            // 每页记录数
            Grid2.PageSize = XConfigHelper.PageSize;
            BindGrid2();
        }

        private void BindGrid()
        {
            SqlQuery q = new Select().From<XRole>();
            q.Where("1").IsEqualTo("1");

            // 排列
            q.OrderBys.Add(GetSortExpression(Grid1, XRole.Schema));

            XRoleCollection items = q.ExecuteAsCollection<XRoleCollection>();

            Grid1.DataSource = items;
            Grid1.DataBind();
        }

        private void BindGrid2()
        {
            XMenuCollection items;

            int roleId = GetSelectedRoleId();
            if (roleId > 0)
            {
                SqlQuery q = new Select().From<XMenu>();
                q.Where("1").IsEqualTo("1");

                // 名称不是AppModule.None
                q.And(XMenu.NameColumn).IsNotEqualTo(ModuleTypeHelper.Module2String(ModuleType.None));

                // 在模块标题中搜索
                string searchText = ttbSearchUser.Text.Trim();
                if (!String.IsNullOrEmpty(searchText))
                {
                    q.And(XMenu.TitleColumn).ContainsString(searchText);
                }

                // 排列
                q.OrderBys.Add(GetSortExpression(Grid2, XMenu.Schema));

                items = q.ExecuteAsCollection<XMenuCollection>();
            }
            else
            {
                Grid2.RecordCount = 0;
                items = new XMenuCollection();
            }

            Grid2.DataSource = RoleModulePowerHelper.GetRoleModulePowers(roleId, items);
            Grid2.DataBind();
        }

        #endregion

        #region Private

        /// <summary>
        /// 获取选中的角色ID（没有则返回-1）
        /// </summary>
        /// <returns></returns>
        private int GetSelectedRoleId()
        {
            int roleId = -1;
            int rowIndex = Grid1.SelectedRowIndex;
            if (rowIndex >= 0)
            {
                roleId = Convert.ToInt32(Grid1.DataKeys[rowIndex][0]);
            }
            return roleId;
        }

        #endregion

        #region Grid1 Events

        protected void Grid1_Sort(object sender, GridSortEventArgs e)
        {
            Grid1.SortColumnIndex = e.ColumnIndex;
            BindGrid();

            // 默认选中第一个角色
            Grid1.SelectedRowIndexArray = new int[] { 0 };

            BindGrid2();
        }

        protected void Grid1_RowClick(object sender, ExtAspNet.GridRowClickEventArgs e)
        {
            BindGrid2();
        }

        #endregion

        #region Grid2 Events

        protected void Grid2_PreRowDataBound(object sender, ExtAspNet.GridPreRowEventArgs e)
        {
            ExtAspNet.CheckBoxField canDeleteField = Grid2.FindColumn("CanDelete") as ExtAspNet.CheckBoxField;
            ExtAspNet.CheckBoxField canEditField = Grid2.FindColumn("CanEdit") as ExtAspNet.CheckBoxField;
            ExtAspNet.CheckBoxField canAddField = Grid2.FindColumn("CanAdd") as ExtAspNet.CheckBoxField;

            RoleModulePower row = e.DataItem as RoleModulePower;
            string moduleName = row.Name;

            List<string> removedModules = RemovedModulePowerTypeHelper.GetRemovedModulePowerTypeDic(moduleName);

            if (removedModules.Contains("CanDelete"))
            {
                canDeleteField.Enabled = false;
            }
            else
            {
                canDeleteField.Enabled = true;
            }

            if (removedModules.Contains("CanEdit"))
            {
                canEditField.Enabled = false;
            }
            else
            {
                canEditField.Enabled = true;
            }

            if (removedModules.Contains("CanAdd"))
            {
                canAddField.Enabled = false;
            }
            else
            {
                canAddField.Enabled = true;
            }

        }

        protected void Grid2_RowDataBound(object sender, ExtAspNet.GridRowEventArgs e)
        {
            AspNet.CheckBoxList ddlOthers = (AspNet.CheckBoxList)Grid2.Rows[e.RowIndex].FindControl("ddlOthers");

            RoleModulePower row = e.DataItem as RoleModulePower;
            string moduleName = row.Name;

            List<string> otherPowerNames = ModulePowerTypeHelper.GetModuleOtherPowerTypeDic(moduleName);

            foreach (string powerName in otherPowerNames)
            {
                // powerName = "ChangePassword" moduleName = "CoreUser"
                AspNet.ListItem item = new AspNet.ListItem();
                item.Value = powerName;
                item.Text = ModulePowerTypeHelper.GetTitle(moduleName, powerName);

                item.Selected = row.OtherPowers[powerName].Value<bool>();

                ddlOthers.Items.Add(item);
            }


            //// 存在其他权限的配置
            //if (otherPowerNames.Count > 0)
            //{
            //    JObject otherPowerObj = new JObject();
            //    if (!String.IsNullOrEmpty(row.Others))
            //    {
            //        otherPowerObj = JObject.Parse(row.Others);
            //    }

            //    foreach (string powerName in otherPowerNames)
            //    {
            //        // powerName = "ChangePassword" moduleName = "CoreUser"
            //        AspNet.ListItem item = new AspNet.ListItem();
            //        item.Value = powerName;
            //        item.Text = AppModuleOtherPowerHelper.GetTitle(String.Format("{0}_{1}", moduleName, powerName));

            //        //JProperty powerProperty = otherPowerObj.Property(powerName);
            //        //if (powerProperty != null)
            //        //{
            //        //    item.Selected = powerProperty.Value.ToObject<bool>();
            //        //}
            //        item.Selected = otherPowerObj.Value<bool?>(powerName) ?? false;

            //        ddlOthers.Items.Add(item);
            //    }
            //}
        }

        protected void ttbSearchUser_Trigger2Click(object sender, EventArgs e)
        {
            ttbSearchUser.ShowTrigger1 = true;
            BindGrid2();
        }

        protected void ttbSearchUser_Trigger1Click(object sender, EventArgs e)
        {
            ttbSearchUser.Text = String.Empty;
            ttbSearchUser.ShowTrigger1 = false;
            BindGrid2();
        }

        protected void Grid2_Sort(object sender, GridSortEventArgs e)
        {
            Grid2.SortColumnIndex = e.ColumnIndex;
            BindGrid2();
        }



        protected void btnGroupUpdate_Click(object sender, EventArgs e)
        {
            int roleId = GetSelectedRoleId();

            // 首先从XRoleModule表中删除所有记录
            XRoleModule.Delete(XRoleModule.RoleIdColumn.ColumnName, roleId);

            // 添加所有记录
            ExtAspNet.CheckBoxField canReadField = Grid2.FindColumn("CanRead") as ExtAspNet.CheckBoxField;
            ExtAspNet.CheckBoxField canDeleteField = Grid2.FindColumn("CanDelete") as ExtAspNet.CheckBoxField;
            ExtAspNet.CheckBoxField canEditField = Grid2.FindColumn("CanEdit") as ExtAspNet.CheckBoxField;
            ExtAspNet.CheckBoxField canAddField = Grid2.FindColumn("CanAdd") as ExtAspNet.CheckBoxField;


            XRoleModuleCollection roleModules = new XRoleModuleCollection();
            foreach (GridRow row in Grid2.Rows)
            {
                int rowIndex = row.RowIndex;

                object[] dataKeys = Grid2.DataKeys[rowIndex];
                // 当前行对应的模块ID
                int moduleId = Convert.ToInt32(dataKeys[0]);
                //string moduleName = dataKeys[1].ToString();

                bool canRead = canReadField.GetCheckedState(rowIndex);
                bool canWrite = canDeleteField.GetCheckedState(rowIndex);
                bool canEdit = canEditField.GetCheckedState(rowIndex);
                bool canAdd = canAddField.GetCheckedState(rowIndex);
                AspNet.CheckBoxList ddlOthers = (AspNet.CheckBoxList)Grid2.Rows[rowIndex].FindControl("ddlOthers");

                JObject otherPowerObj = new JObject();
                foreach (AspNet.ListItem item in ddlOthers.Items)
                {
                    if (item.Selected)
                    {
                        otherPowerObj.Add(item.Value, true);
                    }
                }

                if (canRead || canWrite || canEdit || canAdd || otherPowerObj.Count > 0)
                {
                    XRoleModule roleModule = new XRoleModule();
                    roleModule.RoleId = roleId;
                    roleModule.ModuleId = moduleId;
                    roleModule.CanAdd = canAdd;
                    roleModule.CanDelete = canWrite;
                    roleModule.CanEdit = canEdit;
                    roleModule.CanRead = canRead;
                    if (otherPowerObj.Count > 0)
                    {
                        roleModule.Others = otherPowerObj.ToString();
                    }
                    else
                    {
                        roleModule.Others = "";
                    }

                    roleModules.Add(roleModule);
                }
            }
            roleModules.BatchSave();

            // 更新缓存
            RoleModulePowerHelper.UpdateRoleModulePowerDic(roleId);


            Alert.ShowInTop("当前角色的模块权限更新成功！");
        }

        protected void btnSelectAll_Click(object sender, EventArgs e)
        {
            MenuButton mbtn = sender as MenuButton;
            if (mbtn == mbtnSelectAllSelected)
            {
                SelectAllSelected(true);
            }
            else if (mbtn == mbtnSelectAllCanRead)
            {
                SelectAllCheckBoxField("CanRead", true);
            }
            else if (mbtn == mbtnSelectAllCanDelete)
            {
                SelectAllCheckBoxField("CanDelete", true);
            }
            else if (mbtn == mbtnSelectAllCanEdit)
            {
                SelectAllCheckBoxField("CanEdit", true);
            }
            else if (mbtn == mbtnSelectAllCanAdd)
            {
                SelectAllCheckBoxField("CanAdd", true);
            }
        }

        protected void btnUnSelectAll_Click(object sender, EventArgs e)
        {
            MenuButton mbtn = sender as MenuButton;
            if (mbtn == mbtnUnSelectAllSelected)
            {
                SelectAllSelected(false);
            }
            else if (mbtn == mbtnUnSelectAllCanRead)
            {
                SelectAllCheckBoxField("CanRead", false);
            }
            else if (mbtn == mbtnUnSelectAllCanDelete)
            {
                SelectAllCheckBoxField("CanDelete", false);
            }
            else if (mbtn == mbtnUnSelectAllCanEdit)
            {
                SelectAllCheckBoxField("CanEdit", false);
            }
            else if (mbtn == mbtnUnSelectAllCanAdd)
            {
                SelectAllCheckBoxField("CanAdd", false);
            }
        }


        private void SelectAllCheckBoxField(string columnName, bool selected)
        {
            ExtAspNet.CheckBoxField canField = Grid2.FindColumn(columnName) as ExtAspNet.CheckBoxField;

            for (int i = 0; i < Grid2.Rows.Count; i++)
            {
                string moduleName = Grid2.DataKeys[i][1].ToString();
                List<string> removedModules = RemovedModulePowerTypeHelper.GetRemovedModulePowerTypeDic(moduleName);

                if (!removedModules.Contains(columnName))
                {
                    canField.SetCheckedState(i, selected);
                }
            }
        }

        private void SelectAllSelected(bool selected)
        {
            ExtAspNet.CheckBoxField canReadField = Grid2.FindColumn("CanRead") as ExtAspNet.CheckBoxField;
            ExtAspNet.CheckBoxField canDeleteField = Grid2.FindColumn("CanDelete") as ExtAspNet.CheckBoxField;
            ExtAspNet.CheckBoxField canEditField = Grid2.FindColumn("CanEdit") as ExtAspNet.CheckBoxField;
            ExtAspNet.CheckBoxField canAddField = Grid2.FindColumn("CanAdd") as ExtAspNet.CheckBoxField;

            int[] selectedIndexs = Grid2.SelectedRowIndexArray;
            for (int i = 0; i < selectedIndexs.Length; i++)
            {
                int rowIndex = selectedIndexs[i];
                string moduleName = Grid2.DataKeys[i][1].ToString();
                List<string> removedModules = RemovedModulePowerTypeHelper.GetRemovedModulePowerTypeDic(moduleName);

                
                canReadField.SetCheckedState(rowIndex, selected);
                if (!removedModules.Contains("CanDelete"))
                {
                    canDeleteField.SetCheckedState(rowIndex, selected);
                }
                if (!removedModules.Contains("CanEdit"))
                {
                    canEditField.SetCheckedState(rowIndex, selected);
                }
                if (!removedModules.Contains("CanAdd"))
                {
                    canAddField.SetCheckedState(rowIndex, selected);
                }

                AspNet.CheckBoxList ddlOthers = (AspNet.CheckBoxList)Grid2.Rows[rowIndex].FindControl("ddlOthers");
                foreach (AspNet.ListItem item in ddlOthers.Items)
                {
                    item.Selected = selected;
                }
            }

            Grid2.UpdateTemplateFields();
        }



        #endregion

    }
}
